package com.neusoft.liduan.d0922;

public class Demo5 {
	/*
	 * 5.模拟银行取钱的问题 
	 * 	1.定义一个Account类 
		 * 1）该Account类封装了账户编号（String）和余额（double）两个属性
		 * 2）设置相应属性的getter和setter方法 
		 * 3）提供无参和有两个参数的构造器
		 * 4）系统根据账号判断与用户是否匹配，需提供hashCode()和equals()方法的重写
	 *  2.提供一个取钱的线程类
	 * 		1）提供了Account类的account属性和double类的取款额的属性 2）提供带线程名的构造方法 3）run()方法中提供取钱的操作
	 * 3.在主类中创建线程进行测试。考虑线程安全问题。
	 * 
	 */
	public static void main(String[] args) {
		Account account = new Account();
		account.setCode("001");
		account.setBalance(10000);
		AccountRunnable ar = new AccountRunnable(account);
		ar.setMoney(1000);
		Thread t1 = new Thread(ar, "老爸");
		t1.start();
		Thread t2 = new Thread(ar, "你自己");
		t2.start();
	}
	
	private static class AccountRunnable implements Runnable {
		private Account account;
		private double money;
		
		public void setMoney(double money) {
			this.money = money;
		}
		
		public AccountRunnable(Account account) {
			this.account = account;
		}
		
		@Override
		public synchronized void run() {
			if(account.getBalance() > money) {
				account.setBalance(account.getBalance() - money);
			}
			System.out.println(account.getBalance());
		}
	}
	
	private static class Account {
		private String code;
		private double balance;

		public Account(String code, double balance) {
			super();
			this.code = code;
			this.balance = balance;
		}

		public Account() {

		}

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		public double getBalance() {
			return balance;
		}

		public void setBalance(double balance) {
			this.balance = balance;
		}

		@Override
		public String toString() {
			return "Account [code=" + code + ", balance=" + balance + "]";
		}

		@Override
		public int hashCode() {
			return super.hashCode();
		}
		
		@Override
		public boolean equals(Object obj) {
			if(obj instanceof Account) {
				return this.code.equals(((Account)obj).getCode());
			}
			
			return false;
		}
	}
}
